package org.zmhhxl.user.filter;

import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtRequestFilterTest extends OncePerRequestFilter {

   @Override
   protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
         throws ServletException, IOException {
      final String authorizationHeader = request.getHeader("Authorization");
      log.info("authorizationHeader ===== {}", authorizationHeader);
      //String username = null;
      String jwt = null;
      if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
         jwt = authorizationHeader.substring(7);
         JwtParser jwtParser = Jwts.parser().requireIssuer("http://127.0.0.1:9000").requireSubject("loginType").build();
         log.info("claims ====== {}|{}", jwtParser.parse(jwt).accept(Jws.CONTENT),jwtParser.parse(jwt).accept(Jws.CLAIMS))/*.setSigningKey("secretKey").parseClaimsJws(jwt).getBody().getSubject()*/;
         // 获取自定义 Claim
         //List<String> roles = (List<String>) Jwts.parser().setSigningKey("secretKey").parseClaimsJws(jwt).getBody().get("roles");
         // 将 Claim 设置到请求上下文中
         //request.setAttribute("roles", roles);
      }

      chain.doFilter(request, response);
   }
}
